<template>
  <div class="need-test-man">
    <actions-box :searchForm="[
      { key: 'name', label: '姓名' },
      { key: 'idNumber', label: '身份证号' },
      { key: 'telephone', label: '手机号' },
      { key: 'academy', label: '学院' },
      { key: 'department', label: '部门' }
    ]" :needImportExport="true" @submitSearchRequest="submitSearchRequest" @addItem="showDialog"
      @batchDelete="batchDelete" @batchImport="batchImport" @batchExport="batchExport" @resetTable="getUserList"
      ref="child">
    </actions-box>

    <div class="upload-box-wrapper" v-show="showUploadBox" @click="showUploadBox = false">
      <div class="upload-box" @click.stop="showUploadBox = true">
        <el-upload class="upload-demo" drag :on-success="uploadSuccess" :on-error="uploadError" :headers="headers"
          :action="baseUrl + '/gmu/teacherexcel/submitFile'" multiple>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">只能上传excel文件</div>
        </el-upload>
      </div>
    </div>

    <el-table ref="multipleTable" :data="InfoTable" tooltip-effect="dark" style="width: 100%; margin-top: 20px" border
      stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" fixed align="center"></el-table-column>

      <el-table-column label="序号" align="center" type="index" :index="indexAdd" width="60">
      </el-table-column>

      <el-table-column prop="name" label="姓名" width="80" align="center"></el-table-column>

      <el-table-column prop="sex" width="73" label="性别" sortable align="center">
      </el-table-column>

      <el-table-column prop="telephone" width="110" label="手机号" align="center">
      </el-table-column>

      <el-table-column prop="idNumber" width="165" label="身份证号" align="center">
      </el-table-column>

      <el-table-column prop="academy" width="150" label="学院" align="center">
      </el-table-column>

      <el-table-column prop="department" width="140" label="部门"
        :filters="[{ text: '教务科', value: '教务科' }, { text: '考试管理科', value: '考试管理科' }]" :filter-method="filterMajor"
        align="center">
      </el-table-column>

      <el-table-column prop="icon" width="170" label="操作" align="center">
        <template slot-scope="scope">
          <el-button type="text" @click="showInfo(scope.row)">详情</el-button>
          <el-divider direction="vertical"></el-divider>

          <el-button type="text" @click="editInfo(scope.row)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="确定删除吗？" @confirm="delHandle(scope.row)">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      layout="total, sizes, prev, pager, next, jumper" :page-sizes="[10, 20, 50, 100]" :current-page="current"
      :page-size="size" :total="total">
    </el-pagination>

    <dialog-for-add :dialogVisible="dialogVisible" :info="needShowInfo ? currentInfo : {}" :isEditable="isEditable"
      @refreshTable="getUserList" @closeDialog="closeDialog" :needShowInfo="needShowInfo" fatherComp="teacher">
    </dialog-for-add>
  </div>
</template>

<script>
import ActionsBox from "./subcomps/ActionsBox.vue";
import DialogForAdd from './subcomps/DialogForAdd.vue';
import * as Api from 'api/peopleManagement/teacher.js';
export default {
  name: 'SysTestTeacherManage',
  data() {
    return {
      // 顶部搜索表单
      // 表格信息
      InfoTable: [],
      showUploadBox: false,
      multipleSelection: [], // 已勾选的内容
      // delBtlStatu: true, // 是否未勾选

      headers: {
        // "content-type": 'multipart/form-data',
        "token": localStorage.getItem("token")
      },
      baseUrl: '',

      total: 0, // 总条目数
      size: 10, // 每页表格显示的条数
      current: 1, // 当前页码

      dialogVisible: false, // 新增对话框是否显示

      currentInfo: {},  // 选择的行的信息
      needShowInfo: false, // 是否需要将信息展示到dialog
      isEditable: true, // 是否可编辑dialog
    };
  },
  components: {
    ActionsBox,
    DialogForAdd
  },
  created() {
    this.baseUrl = this.$baseUrl;
    this.getUserList()
  },
  methods: {
    // 实现表格序号自增
    indexAdd(index) {
      return index + 1 + (this.current - 1) * this.size;
    },
    // params即为子组件传递过来的值
    submitSearchRequest(params) {
      Api.getTeacherByCondition(params).then(res => {
        this.InfoTable = res.data.data;
        console.log('搜索结果：', res);
      }).catch(err => {
        console.log('搜索失败：', err);
      })
      console.log('params: ', params);
    },
    // 展示‘新增’对话框
    showDialog() {
      this.dialogVisible = true;
    },
    // 批量删除
    batchDelete() {
      const userIds = this.multipleSelection.map(val => {
        return val.userId;
      })
      Api.deleteTeachersInBatches(userIds.toString()).then(res => {
        this.getUserList();
        this.$message({
          message: "删除成功",
          type: "success"
        })
      }).catch(err => {
        console.log("批量删除用户：", err);
      })
    },
    // res 表示请求响应体
    uploadSuccess(res, file, filelist) {
      if (res.code == '200') {
        this.getUserList();
        this.$message.success("上传成功");
        this.showUploadBox = false;
      } else {
        this.$message.error("上传失败");
      }
    },
    uploadError(err, file, filelist) {
      this.$message.error("上传失败");
    },
    // 批量导入
    batchImport() {
      this.showUploadBox = true;
    },
    // 批量导出
    batchExport() {
      Api.batchExportTeachers().then(res => {
        let blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        let filename = window.decodeURI(res.headers['content-disposition']).split('=')[1]
        let url = window.URL.createObjectURL(blob)
        let aLink = document.createElement("a")
        aLink.style.display = "none"
        aLink.href = url
        aLink.setAttribute("download", filename)
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink)
        window.URL.revokeObjectURL(url)
        console.log('导出成功：', res)
      }).catch(err => {
        console.log('导出失败：', err)
      })
    },

    // 勾选后触发
    handleSelectionChange(val) {
      console.log("勾选项：", val);
      // 获取所有勾选项
      this.multipleSelection = val;

      this.delBtlStatu = val.length == 0;
      this.$refs.child.delBtlStatu = this.delBtlStatu;
      console.log(this.$refs.child.delBtlStatu)
    },

    // 筛选检测状态（未检测，已检测）
    filterStatus(value, row) {
      return row.status === value;
    },
    // 筛选学院
    filterAcademy(value, row) {
      return row.academy === value;
    },
    // 筛选专业
    filterMajor(value, row) {
      return row.major === value;
    },
    // 暂不知
    filterHandler(value, row, column) {
      console.log(value, row, column);
      const property = column["property"];
      return row[property] === value;
    },
    // 分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val;
      this.getUserList();
    },
    // 获取当前页信息
    getUserList() {
      const pageInfo = {
        current: this.current,
        size: this.size
      };
      Api.getCurrentPageTeachers(pageInfo).then(res => {
        // this.tableData = res.data.data.records
        // this.size = res.data.data.size
        // this.current = res.data.data.current
        // this.total = res.data.data.total
        console.log('老师信息：', res);
        this.total = res.data.data.total;
        this.InfoTable = res.data.data.rows;
      });
    },
    // 关闭dialog
    closeDialog() {
      this.needShowInfo = false;
      this.dialogVisible = false;
      this.currentInfo = {};
      this.isEditable = true;
    },
    // 编辑信息
    editInfo(info) {
      this.needShowInfo = true;
      this.showDialog();
      this.currentInfo = info;
    },
    // 展示信息
    showInfo(info) {
      console.log("info: ", info);
      this.needShowInfo = true;
      this.isEditable = false;
      this.showDialog();
      this.currentInfo = info;
    },

    // 删除用户
    delHandle(info) {
      this.$axios.delete("/gmu/tbl-teacher/deleteTeacher/" + info.teacherId).then(res => {
        this.getUserList();
        this.$message({
          message: "删除成功",
          type: "success"
        })
      }).catch(err => {
        console.log("删除用户：", err);
      })
    },
  },
};
</script>

<style>
.action-btns {
  display: flex;
  justify-content: space-between;
}

.action-btns>div {
  display: inline-block;
}
</style>
